import React, {Component, Fragment} from 'react';
import { Button } from '@alifd/next';
import styles from './index.module.scss';

export default class CountDownbutton extends Component {
    static displayName = 'Index';

    static propTypes = {};

    static defaultProps = {};

    constructor(props) {
        super(props);
        this.state = {
            time: 60,
            btnDisable:false,
            btnContent: '发送验证码'
        };
    }

    render() {
        let timeChange;
        let ti = this.state.time;
        //关键在于用ti取代time进行计算和判断，因为time在render里不断刷新，但在方法中不会进行刷新
        const clock =()=>{
            if (ti > 0) {
                //当ti>0时执行更新方法
                ti = ti - 1;
                this.setState({
                    time: ti,
                    btnContent: ti + "s后重试",
                });
                console.log(ti);
            }else{
                //当ti=0时执行终止循环方法
                clearInterval(timeChange);
                this.setState({
                    btnDisable: false,
                    time: 60,
                    btnContent: "重发验证码",
                });
            }
        };

        const sendCode = () =>{
            this.setState({
                btnDisable: true,
                btnContent: "60s后重试",
            });
            //每隔一秒执行一次clock方法
            timeChange = setInterval(clock,1000);
        };

        return (
            <Fragment>
                <Button type="primary" size="medium" inline onClick={sendCode} disabled={this.state.btnDisable}>{this.state.btnContent}</Button>
            </Fragment>
        );
    }
};
